package com.coldtech.circlecrash;

import java.util.ArrayList;
import java.util.List;

import com.coldtech.circlecrash.units.Unit;

public class Square {
	public final class SquareBlock {
		private List<Square> block;

		public SquareBlock(Square square) {
			block = new ArrayList<Square>();
			block.add(square);
		}

		public void add(Square square) {
			block.add(square);
		}

		public boolean contains(Unit unit) {
			for (int i = 0; i < block.size(); i++) {
				if (block.get(i).isInSquare(unit)) {
					return true;
				}
			}
			return false;
		}

		public Square containIn(Unit unit) {
			Square sq = null;
			for (int i = 0; i < block.size(); i++) {
				sq = block.get(i);
				if (block.get(i).isInSquare(unit)) {
					return sq;
				}
			}
			return null;
		}

		public List<Square> getSquares() {
			return block;
		}

		public List<Unit> getUnits() {
			List<Unit> units = new ArrayList<Unit>();
			Square sq = null;
			for (int i = 0; i < block.size(); i++) {
				sq = block.get(i);
				for (int j = 0; j < sq.getUnits().size(); j++) {
					units.addAll(sq.getUnits());
				}
			}
			return units;
		}
	}

	public static final int WIDTH = 50;
	public static final int HEIGHT = 50;
	private final int posX, posY, maxX, maxY;
	private List<Unit> units;
	private SquareBlock squareBlock;
	private String name;

	public Square(final String name, final int posX, final int posY) {
		this.name = name;
		this.posX = posX;
		this.posY = posY;
		this.maxX = posX + WIDTH;
		this.maxY = posY + HEIGHT;
		units = new ArrayList<Unit>();
		squareBlock = new SquareBlock(this);
	}

	public void addSquareToBlock(Square square) {
		squareBlock.add(square);
	}

	public boolean isInSquare(Unit unit) {
		return ((unit.getPosition().getX() >= posX && unit.getPosition().getX() < maxX) && (unit
				.getPosition().getY() >= posY && unit.getPosition().getY() < maxY));
	}

	public boolean isInSquare(int x, int y) {
		return ((x >= posX && x < maxX) && (y >= posY && y < maxY));
	}

	public void addUnit(Unit unit) {
		units.add(unit);
	}

	public void removeUnit(Unit unit) {
		units.remove(unit);
	}

	public List<Unit> getUnits() {
		return units;
	}

	public SquareBlock getSquareBlock() {
		return squareBlock;
	}

	public int getX() {
		return posX;
	}

	public int getY() {
		return posY;
	}

	public String getName() {
		return name;
	}
}
